<?php
include('db.inc.php');
include('user.class.php');
header('X-Frame-Options: SAMEORIGIN');
if (!isEmpty(getParam("sid"))) {
    session_id(getParam("sid"));
    session_start();
} else {
    @session_start();
}
if (!defined("CFG_PATH")) {
    define("CFG_PATH", $_SESSION["CFG_PATH"]);
}
include_once(CFG_PATH );
$user = null;
if ($_SESSION['user'] == NULL) {
    header('Location: ../../login.php');
} else {
    $user = unserialize($_SESSION['user']);
}
define('DB_CHARSET', 'utf8');
$db = new DbManager();
$db->connect(DBHOST, DBUSER, DBPWD, true, true, DBNAME, "");

define('DATE_PATTERN_MYSQL', '%Y-%m-%d');
define('DATE_PATTERN', 'Y-m-d');
define('TIME_PATTERN', 'H:i');
define('FORMAT', 'Y-m-d');

function getCycle($db, $user) {
    $cy = $db->query_select("cllg_college_cycle", "CODE=" . $user->cycle . " AND FK_ENTITY=" . $user->entity);
    $cy = $cy[0];
}

function getTotalAbono($db, $idCargo) {
    $sql = sprintf("SELECT sum(a.MONTO) as tot FROM
  cllg_mov_cargo a where a.FK_CARGO=%s", $idCargo);

    $rs = $db->query_toArray($sql);
    if (count($rs) > 0) {
        return $rs[0]["tot"];
    }
    return 0;
}

function findStudentAssigns($db, $student, $career, $user) {
    $cy = $db->query_select("cllg_student_assign", "FK_CYCLE=" . $user->cycle . " AND FK_STUDENT=" . $student .
            " AND FK_ENTITY=" . $user->entity . " AND FK_CAREER=" . $career . " AND STATUS=1");
    return count($cy);
}

function listStudentAssigns($db, $student, $user) {
    $cy = $db->query_select("cllg_student_assign", "FK_STUDENT=" . $student .
            " AND FK_ENTITY=" . $user->entity);
    return $cy;
}

function findTeacherAssigns($db, $teacher, $user, $course = NULL, $section = NULL) {
    $where = "FK_CYCLE=" . $user->cycle . " AND FK_TEACHER=" . sqlValue($teacher, "text");
    if ($course != NULL) {
        $where.=" AND FK_COURSE=" . $course;
    }
    if ($section != NULL) {
        $where.=" AND SECTION=" . sqlValue($section, "text");
    }
    $cy = $db->query_select("cllg_teacher_assign", $where);
    return count($cy);
}

function getFRFieldContent($table, $where, $fname, $db) {
    $c = $db->query_select($table, $where, null);
    return $c[0][$fname];
}

function getCarrers($db) {
    return $db->query_select("cllg_career", null);
}

function getPensumByCarerr($db, $idCarrera) {
    return $db->query_select("cllg_pensum", "FK_CAREER=" . $idCarrera);
}

function getCoursesByPensum($db, $idPensum) {
    $sql = "SELECT a.CODE,a.NAME FROM cllg_courses_catalog a,cllg_courses_pensum b WHERE ";
    $sql.="a.FK_COURSE=b.CODE AND a.FK_PENSUM=" . $idPensum;
    return $db->queryToArray($sql);
}

function getCareerName($id, $db) {
    return getFRFieldContent("cllg_career", "ID=" . $id, "NAME", $db);
}

function getCourseName($id, $db) {
    return getFRFieldContent("cllg_courses_catalog", "CODE=" . $id, "NAME", $db);
}

function getTeachName($id, $db) {
    $fName = getFRFieldContent("cllg_teacher", "ID=" . $id, "FIRST_NAME", $db);
    $lName = getFRFieldContent("cllg_teacher", "ID=" . $id, "LAST_NAME", $db);
    return $fName . " " . $lName;
}

function myExceptionHandler($e) {
    echo "<h1>Technical error</h1>";
    echo "<pre>";
    echo $e;
    echo "</pre>";
}

function sqlValue($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") {
    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
    $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

    switch ($theType) {
        case "text":
            $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
            break;
        case "int":
            $theValue = ($theValue != "") ? intval($theValue) : "NULL";
            break;
        case "double":
            $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
            break;
        case "date":
            $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
            break;
        case "defined":
            $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
            break;
    }
    return $theValue;
}

function isEmpty($str) {
    return (strlen(trim($str)) == 0) || ($str == "null");
}

function getFieldValue($db, $tableName, $pkRecord, $fieldName, $singleValue = 0) {
    $sql = "SELECT A.NAME,B.VALUE FROM cllg_tablefield A LEFT JOIN
	  		cllg_table_valuebyfield B ";
    $sql.=sprintf("ON (A.NAME=B.FK_TABLEFIELD AND B.PK_RECORD='%s') ", $pkRecord);
    $sql.=sprintf("WHERE B.FK_TABLEFIELD='%s' ", $fieldName);
    $sql.=sprintf("AND A.TABLE_NAME='%s' ", $tableName);
    $sql.="AND A.STATUS=1";
    $rs = $db->fetch_all_array($db->query($sql));
    if ($singleValue > 0) {
        return $rs[0]["VALUE"];
    }
    return $rs;
}

function getParam($name, $default = null) {
    if (array_key_exists($name, $_REQUEST)) {
        $param = str_replace('\"', '"', $_REQUEST[$name]); //PARCHE PARA VERSION json_1.2.1
        if ($default != null && isEmpty($param)) {
            return $default;
        }
        return $param;
    }
    else
        return $default;
}

function getRowsToInsert() {
    $rows = array();
    if ($_SESSION["lastFile"] != null) {
        // instancing new CSVReader object reading a file 'sample.csv'
        $reader = new CSVReader(new FileReader($_SESSION["lastFile"]));
        // set the separator use format, here a comma
        $reader->setSeparator(',');

        while (false != ( $cell = $reader->next() )) {
            $rows[] = $cell;  //carnet,nota
        }
    }
    return $rows;
}

function includeModules($dir) {

    if (is_dir($dir)) {
        $files = array();
        $dirs = array();

        $dh = opendir($dir);
        while (false !== ($filename = readdir($dh))) {
            if (substr($filename, 0, 1) != '.' and $filename != 'CVS') {
                $files[] = $filename;
            }
        }
        closedir($dh);

        for ($i = 0; $i < count($files); $i++) {
            if (is_dir("$dir/{$files[$i]}")) {
                $dirs[] = "$dir/{$files[$i]}";
            } elseif (is_file("$dir/{$files[$i]}") and (substr($files[$i], -4) == '.php')) {
                require_once "$dir/{$files[$i]}";
            }
        }

        foreach ($dirs as $subdir) {
            includeModules($subdir);
        }
    }
}

/* ! 
  @function num2letras ()
  @abstract Dado un n?mero lo devuelve escrito.
  @param $num number - N?mero a convertir.
  @param $fem bool - Forma femenina (true) o no (false).
  @param $dec bool - Con decimales (true) o no (false).
  @result string - Devuelve el n?mero escrito en letra.
  <? echo num2letras('15000'); ?>
 */

function num2letras($num, $fem = true, $dec = true) {
//if (strlen($num) > 14) die("El n?mero introducido es demasiado grande");
    $matuni[2] = "dos";
    $matuni[3] = "tres";
    $matuni[4] = "cuatro";
    $matuni[5] = "cinco";
    $matuni[6] = "seis";
    $matuni[7] = "siete";
    $matuni[8] = "ocho";
    $matuni[9] = "nueve";
    $matuni[10] = "diez";
    $matuni[11] = "once";
    $matuni[12] = "doce";
    $matuni[13] = "trece";
    $matuni[14] = "catorce";
    $matuni[15] = "quince";
    $matuni[16] = "dieciseis";
    $matuni[17] = "diecisiete";
    $matuni[18] = "dieciocho";
    $matuni[19] = "diecinueve";
    $matuni[20] = "veinte";
    $matunisub[2] = "dos";
    $matunisub[3] = "tres";
    $matunisub[4] = "cuatro";
    $matunisub[5] = "quin";
    $matunisub[6] = "seis";
    $matunisub[7] = "sete";
    $matunisub[8] = "ocho";
    $matunisub[9] = "nove";

    $matdec[2] = "veint";
    $matdec[3] = "treinta";
    $matdec[4] = "cuarenta";
    $matdec[5] = "cincuenta";
    $matdec[6] = "sesenta";
    $matdec[7] = "setenta";
    $matdec[8] = "ochenta";
    $matdec[9] = "noventa";
    $matsub[3] = 'mill';
    $matsub[5] = 'bill';
    $matsub[7] = 'mill';
    $matsub[9] = 'trill';
    $matsub[11] = 'mill';
    $matsub[13] = 'bill';
    $matsub[15] = 'mill';
    $matmil[4] = 'millones';
    $matmil[6] = 'billones';
    $matmil[7] = 'de billones';
    $matmil[8] = 'millones de billones';
    $matmil[10] = 'trillones';
    $matmil[11] = 'de trillones';
    $matmil[12] = 'millones de trillones';
    $matmil[13] = 'de trillones';
    $matmil[14] = 'billones de trillones';
    $matmil[15] = 'de billones de trillones';
    $matmil[16] = 'millones de billones de trillones';

    $num = trim((string) @$num);
    if ($num[0] == '-') {
        $neg = 'menos ';
        $num = substr($num, 1);
    }
    else
        $neg = '';
    while ($num[0] == '0')
        $num = substr($num, 1);
    if ($num[0] < '1' or $num[0] > 9)
        $num = '0' . $num;
    $zeros = true;
    $punt = false;
    $ent = '';
    $fra = '';
    for ($c = 0; $c < strlen($num); $c++) {
        $n = $num[$c];
        if (!(strpos(".,'''", $n) === false)) {
            if ($punt)
                break;
            else {
                $punt = true;
                continue;
            }
        } elseif (!(strpos('0123456789', $n) === false)) {
            if ($punt) {
                if ($n != '0')
                    $zeros = false;
                $fra .= $n;
            }
            else
                $ent .= $n;
        }
        else
            break;
    }
    $ent = '     ' . $ent;
    if ($dec and $fra and !$zeros) {
        $fin = ' coma';
        for ($n = 0; $n < strlen($fra); $n++) {
            if (($s = $fra[$n]) == '0')
                $fin .= ' cero';
            elseif ($s == '1')
                $fin .= $fem ? ' una' : ' un';
            else
                $fin .= ' ' . $matuni[$s];
        }
    }
    else
        $fin = '';
    if ((int) $ent === 0)
        return 'Cero ' . $fin;
    $tex = '';
    $sub = 0;
    $mils = 0;
    $neutro = false;
    while (($num = substr($ent, -3)) != '   ') {
        $ent = substr($ent, 0, -3);
        if (++$sub < 3 and $fem) {
            $matuni[1] = 'una';
            $subcent = 'as';
        } else {
            $matuni[1] = $neutro ? 'un' : 'uno';
            $subcent = 'os';
        }
        $t = '';
        $n2 = substr($num, 1);
        if ($n2 == '00') {
            
        } elseif ($n2 < 21)
            $t = ' ' . $matuni[(int) $n2];
        elseif ($n2 < 30) {
            $n3 = $num[2];
            if ($n3 != 0)
                $t = 'i' . $matuni[$n3];
            $n2 = $num[1];
            $t = ' ' . $matdec[$n2] . $t;
        }else {
            $n3 = $num[2];
            if ($n3 != 0)
                $t = ' y ' . $matuni[$n3];
            $n2 = $num[1];
            $t = ' ' . $matdec[$n2] . $t;
        }
        $n = $num[0];
        if ($n == 1) {
            $t = ' ciento' . $t;
        } elseif ($n == 5) {
            $t = ' ' . $matunisub[$n] . 'ient' . $subcent . $t;
        } elseif ($n != 0) {
            $t = ' ' . $matunisub[$n] . 'cient' . $subcent . $t;
        }
        if ($sub == 1) {
            
        } elseif (!isset($matsub[$sub])) {
            if ($num == 1) {
                $t = ' mil';
            } elseif ($num > 1) {
                $t .= ' mil';
            }
        } elseif ($num == 1) {
            $t .= ' ' . $matsub[$sub] . '?n';
        } elseif ($num > 1) {
            $t .= ' ' . $matsub[$sub] . 'ones';
        }
        if ($num == '000')
            $mils++;
        elseif ($mils != 0) {
            if (isset($matmil[$sub]))
                $t .= ' ' . $matmil[$sub];
            $mils = 0;
        }
        $neutro = true;
        $tex = $t . $tex;
    }
    $tex = $neg . substr($tex, 1) . $fin;
    return ucfirst($tex);
}

function getDiasMes($anho, $mes) {
    if (((fmod($anho, 4) == 0) and (fmod($anho, 100) != 0)) or (fmod($anho, 400) == 0)) {
        $dias_febrero = 29;
    } else {
        $dias_febrero = 28;
    }
    switch ($mes) {
        case 01: return 31;
            break;
        case 02: return $dias_febrero;
            break;
        case 03: return 31;
            break;
        case 04: return 30;
            break;
        case 05: return 31;
            break;
        case 06: return 30;
            break;
        case 07: return 31;
            break;
        case 08: return 31;
            break;
        case 09: return 30;
            break;
        case 10: return 31;
            break;
        case 11: return 30;
            break;
        case 12: return 31;
            break;
    }
}

function getDatesDif($f1, $f2) {  //Y-m-d format
    $dia1 = date("d", strtotime($f1));
    $mes1 = date("m", strtotime($f1));
    $ano1 = date("Y", strtotime($f1));

    $dia2 = date("d", strtotime($f2));
    $mes2 = date("m", strtotime($f2));
    $ano2 = date("Y", strtotime($f2));

    //calculo timestam de las dos fechas
    $timestamp1 = mktime(0, 0, 0, $mes1, $dia1, $ano1);
    $timestamp2 = mktime(4, 12, 0, $mes2, $dia2, $ano2);

    //resto a una fecha la otra
    $segundos_diferencia = $timestamp1 - $timestamp2;
    //echo $segundos_diferencia;
    //convierto segundos en d�as
    $dias_diferencia = $segundos_diferencia / (60 * 60 * 24);

    //obtengo el valor absoulto de los d�as (quito el posible signo negativo)
    $dias_diferencia = abs($dias_diferencia);

    //quito los decimales a los d�as de diferencia
    $dias_diferencia = floor($dias_diferencia);

    return $dias_diferencia;
}

function drawDebug($ThisVar, $VariableName = "", $ShowWhat = 0, $boolForceShow = false) {

    $strType = gettype($ThisVar);
    $strPreOpen = "";
    $strPreClose = "";
    if (!is_string($ThisVar)) {
        $strPreOpen = "<pre>";
        $strPreClose = "</pre>";
    }

    echo "\n<hr>";
    if (!empty($VariableName))
        echo "<b><i> $VariableName</b></i> ";
    echo "Var  Type of var = <b>" . $strType . "</b><br><br>\n{$strPreOpen}";
    if ($ShowWhat == 0) {
        if (is_bool($ThisVar))
            print_r(($ThisVar) ? "true" : "false");
        else
            print_r($ThisVar);
    }

    else if ($ShowWhat == 1) {
        print_r(array_values($ThisVar));
    } else if ($ShowWhat == 2) {
        print_r(array_keys($ThisVar));
    }
    print_r("<hr>{$strPreClose}\n");
}

?>